# _*_ coding:utf-8 _*_
# @Time  : 2023.02.27
# @Author: zizlee

import pathlib
import fitz
import pythoncom
import win32com.client


def ppt2pdf(filename, output_filename: pathlib.Path, is_image=False):
    # 打开PPT程序
    pythoncom.CoInitialize()
    ppt_app = win32com.client.gencache.EnsureDispatch('PowerPoint.Application')
    # ppt_app.Visible = True  # 程序操作应用程序的过程是否可视化
    # oQmNjBelKngstGzX.pptximg  filename
    # 通过PPT的应用程序打开指定的PPT文件
    # filename = "C:/Users/Administrator/Desktop/PPT办公自动化/ppt/PPT素材1.pptx"
    # output_filename = "C:/Users/Administrator/Desktop/PPT办公自动化/ppt/PPT素材1.pdf"
    ppt = ppt_app.Presentations.Open(filename)
    # 打开的PPT另存为pdf文件。17数字是ppt转图片，32数字是ppt转pdf。 17:jpg 18:png 19:bmp
    flag = 17 if is_image else 32
    ppt.SaveAs(output_filename, flag)
    # 退出PPT程序
    ppt.Close()
    ppt_app.Quit()  # 这行代码没有起作用，但也没报错。无语..
    # close_by_force(ppt_app)  # 强制关闭程序
    if is_image:
        # 重命名文件夹
        r = output_filename.parent.joinpath(output_filename.name.replace(output_filename.suffix, ''))
        if r.exists() and not r.is_file():
            r.rename(output_filename)
        # 读取文件夹下的所有jpg图片
        image_files = output_filename.glob('*.jpg')
        if len(list(image_files)) < 1:
            for n, img in enumerate(output_filename.glob('*' + output_filename.suffix)):
                img.rename(output_filename.joinpath(f'幻灯片{n+1}.JPG'))
            image_files = output_filename.glob('*.jpg')
        num_sorted = [int(i.name.replace('幻灯片', '').replace('.jpg', '').replace('.JPG', '')) for i in image_files]
        num_sorted.sort()
        return [output_filename.joinpath(f'幻灯片{n}.JPG') for n in num_sorted]
    return output_filename


def docx2pdf(filename, output_filename):
    pythoncom.CoInitialize()
    word = win32com.client.gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(filename)
    doc.ExportAsFixedFormat(output_filename,
                            win32com.client.constants.wdExportFormatPDF,
                            Item=win32com.client.constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=win32com.client.constants.wdExportCreateHeadingBookmarks)
    doc.Close()
    word.Quit(win32com.client.constants.wdDoNotSaveChanges)
    return output_filename


def pdf2image(filename, out_folder: pathlib.Path):
    image_list = []
    doc = fitz.open(filename)  # open document
    matrix = fitz.Matrix(1.5, 1.5)  # 放大
    for page in doc:  # iterate through the pages
        pix = page.get_pixmap(matrix=matrix)  # render page to an image
        image_name = out_folder.joinpath('page_%03d.png' % page.number)
        pix.save(image_name)  # store image as a PNG
        image_list.append(image_name)
    doc.close()
    return image_list


